package com.younion.business.impl;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.younion.beans.TabRefBean;
import com.younion.business.ICommonDelService;
import com.younion.common.exception.BaseException;
import com.younion.dao.CommonDelDAO;
import com.younion.spring.CommonDelResBean;

public class CommonDelServiceImpl extends BaseService implements ICommonDelService {
	
	protected static final Log logger = LogFactory.getLog(CommonDelServiceImpl.class);

	private CommonDelDAO commonDelDAO;
	
	public void setCommonDelDAO(CommonDelDAO commonDelDAO) {
		this.commonDelDAO = commonDelDAO;
	}

	public CommonDelResBean getRefCount(TabRefBean bean) throws BaseException {
		Properties props = bean.getTbAttributes();
		Properties others = bean.getOtherAttributes();
		Object[] arr = props.keySet().toArray();
		String select = "select concat(";
		String from = "";
		CommonDelResBean cdrb = new CommonDelResBean();
		cdrb.setFlag(true);
		for (int i = 0; i < arr.length; i++) {
			Object key = arr[i];
			select += "t"+i+".r_count,',',";
			from += "(select count(1) r_count from "+key+" where "+props.get(key)+" in(";
			if (others != null && others.get(key) != null) {
				from += "select "+others.get(key)+" from "+bean.getTbName()+" where "+bean.getTbId()+" in("+bean.getIds()+")";
			} else {
				from += bean.getIds();
			}
			from += "))t"+i+",";
		}
		select = select.substring(0, select.length()-1)+")a_count from ";
		from = from.substring(0, from.length()-1);
		try {
			String resStr = this.commonDelDAO.getRefCount(select+from);
			String counts[] = resStr.split(",");
			for (String temp : counts) {
				if (!temp.equals("0")) {
					cdrb.setFlag(false);
					cdrb.setErrorInfo("引用数据不为空，请先删除引用数据！");
					break;
				}
			}
			return cdrb;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(CommonDelServiceImpl.class.getName()+" >> public CommonDelResBean getRefCount(TabRefBean bean) error occur:", e);
		}
	}

}
